//
//  LeaveWordsViewController.m
//  RainbowFM
//
//  Created by Kratos on 14/12/14.
//  Copyright (c) 2014年 RB. All rights reserved.
//

#import "LeaveWordsViewController.h"

#import "LeaveWordsCompereHeadView.h"
#import "LeaveWordsCompereCell.h"
#import "LeaveWoedsSpectatorCell.h"
#import "TextInputView.h"
#import "DAKeyboardControl.h"
#import "PhotosViewController.h"

//#import "Track.h"
#import "CompereModel.h"
#import "UserModel.h"
//#import "DOUAudioStreamer.h"
#import "PlayAudioManager.h"

#import "FileUpLoadAPI.h"

#import <AFNetworking/AFNetworking.h>
#import "AFAppDotNetAPIClient.h"

static void *kStatusKVOKey = &kStatusKVOKey;

@interface LeaveWordsViewController () <TextInputViewDelegate,UITableViewDelegate,UITableViewDataSource,PlayAudioManagerDelegate>
@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) LeaveWordsCompereHeadView *headView;

@property (nonatomic , strong) NSMutableArray *listArr;

@property (nonatomic , strong) NSIndexPath *voicingIndexPath;
@property (nonatomic , strong) PlayAudioManager *videoPlayer;
//@property (strong, nonatomic) DOUAudioStreamer *streamer;
//@property (strong, nonatomic) Track *track;

@end

@implementation LeaveWordsViewController

-(void)awakeFromNib
{
    _listArr = [NSMutableArray array];
    _videoPlayer = [PlayAudioManager sharedManager];
    _videoPlayer.delegatePlayingCompleteOrUserStop = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatKeyBoard];
    [self setHead:_part];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    
    if (_videoPlayer && _videoPlayer.isPlaying) {
        [_videoPlayer stopPlaying];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setHead:(InterlocutionPart)part
{
    typeof(self) self_ = self;
    switch (part) {
        case InterlocutionPartOfCompere:
        {
            if (!_headView) {
                _headView = _LoadXib(LeaveWordsCompereHeadView, nil, nil);
                [_headView.headImageView sd_setImageWithURL:[NSURL URLWithString:_compereitem ? _compereitem.anchorHeadPic : @""]];
                [_headView.nameLabel setText:_compereitem ? _compereitem.anchorName : @""];
                [_headView.causerieLabel setText:_compereitem ? _compereitem.content : @""];
                [_tableView setTableHeaderView:_headView];
            }
            
            
            [[CompereModel sharedModel]fetchLeaveWordsListWithCmtType:CommentTypeForCompereLeave cmtTarget:_cmtTarget reqType:RequestTypeAll pageSize:200 currentPage:1 result:^(NSArray *list, NSString *msg) {
                [self_.listArr removeAllObjects];
                for (LeaveWordItem *item in list) {
                    item.leaveWordType = 1;
                    [self_.listArr addObject:item];
                }
                
                [self_.tableView reloadData];
                
            }];
            
        }
            break;
        case InterlocutionPartOfSpectator:
        {
            [[CompereModel sharedModel] fetchLeaveWordsListWithCmtType:CommentTypeForLiveLeave cmtTarget:_cmtTarget reqType:RequestTypeAll pageSize:200 currentPage:1 result:^(NSArray *list, NSString *msg) {
                [self_.listArr removeAllObjects];
                for (LeaveWordItem *item in list) {
                    item.leaveWordType = 1;
                    [self_.listArr addObject:item];
                }
                
                [self_.tableView reloadData];
            }];
        }
            break;
        case InterlocutionPartOfMyself:
        {
            [self setTitle:@"意见反馈"];
            UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 30.f)];
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10.f, 5.f, 200.f, 20.f)];
            [label setText:@"我的留言:"];
            [label setFont:[UIFont systemFontOfSize:18]];
            [backView addSubview:label];
            
            [_tableView setTableHeaderView:backView];
            
            _cmtTarget = Feedback_CmtTarget;
            [[CompereModel sharedModel]fetchLeaveWordsListWithCmtType:CommentTypeForFeedback cmtTarget:_cmtTarget reqType:RequestTypeMy pageSize:200 currentPage:1 result:^(NSArray *list, NSString *msg) {
                [self_.listArr removeAllObjects];
                for (LeaveWordItem *item in list) {
                    item.leaveWordType = 1;
                    [self_.listArr addObject:item];
                }
                
                [self_.tableView reloadData];
            }];
        }
            break;
        default:
            break;
    }
}

-(void)creatKeyBoard
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64.f,CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 114.f)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.1]];
    [self.view addSubview:_tableView];
    
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f,
                                                                     self.view.bounds.size.height - 50.0f,
                                                                     self.view.bounds.size.width,
                                                                     50.0f)];
    toolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:toolBar];
    
    TextInputView *textInputView = _LoadXib(TextInputView, nil, nil);
    textInputView.delegate = self;
    textInputView.frame = toolBar.bounds;
    [toolBar addSubview:textInputView];
    
    self.view.keyboardTriggerOffset = toolBar.bounds.size.height;
    
    [self.view addKeyboardPanningWithActionHandler:^(CGRect keyboardFrameInView) {
        
        CGRect toolBarFrame = toolBar.frame;
        toolBarFrame.origin.y = keyboardFrameInView.origin.y - toolBarFrame.size.height;
        toolBar.frame = toolBarFrame;
            
    }];

}

#pragma mark - table datasource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LeaveWordItem *item = _listArr[indexPath.row];
    CGFloat h = 70.f;
    switch (item.type) {
        case 1:
            h = [LeaveWordsTableViewCell cellHightByText:item.cmtContent];
            break;
        case 2:
            h = [LeaveWoedsSpectatorCell cellHightByImage];
            break;
        case 3:
            h = [LeaveWoedsSpectatorCell cellHightByVoice];
            break;
        default:
            break;
    }
    
    
    return h;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_listArr count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LeaveWordItem *item = _listArr[indexPath.row];
    
    InterlocutionPart part = item.leaveWordType;
    switch (part) {
        case InterlocutionPartOfCompere:
        case InterlocutionPartOfSpectator:
        {
            LeaveWordsCompereCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeaveWordsCompereCell"];
            if (!cell) {
                cell = _LoadXib(LeaveWordsCompereCell, nil, nil);
                [cell setBackgroundColor:[UIColor clearColor]];
            }
            
            [cell updateContentsWithItem:item];
            
            if (_voicingIndexPath && _voicingIndexPath.row == indexPath.row) {
                [cell startVoice];
            }
            
            return cell;
        }
            break;
        case InterlocutionPartOfMyself:
        {
            LeaveWoedsSpectatorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeaveWoedsSpectatorCell"];
            if (!cell) {
                cell = _LoadXib(LeaveWoedsSpectatorCell, nil, nil);
                [cell setBackgroundColor:[UIColor clearColor]];
            }
            
            [cell updateContentsWithItem:item];
            
            if (_voicingIndexPath && _voicingIndexPath.row == indexPath.row) {
                [cell startVoice];
            }
            
            return cell;
        }
            break;
        default:
            return nil;
            break;
    }
    
}




#pragma mark - table delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LeaveWordItem *item = _listArr[indexPath.row];
    switch (item.type) {
        case 1://文字
            
            break;
        case 2://图片
        {
            PhotosViewController *photosViewController = [PhotosViewController new];
            [photosViewController setImageUrls:@[item.picUrl]];
            [self.navigationController pushViewController:photosViewController animated:YES];
        }
            break;
        case 3://语言
        {
            LeaveWordsTableViewCell *cell = _voicingIndexPath ? (LeaveWordsTableViewCell *)[_tableView cellForRowAtIndexPath:_voicingIndexPath] : nil;
            
            if (cell) {
                [cell stopVoice];
            }
            
            _voicingIndexPath = indexPath;
            [self playTrafficRadio:item];
        }
            break;
        default:
            break;
    }
}

#pragma mark - TextInputViewDelegate
-(void)textSended:(NSString *)text view:(TextInputView *)view
{
    if (text && text.length > 0) {
        [SVProgressHUD show];
        [self sendData:text type:LeaveWordsTypeOfText];
    }
    
}

-(void)imageSendedWithImage:(UIImage *)image imageData:(NSData *)imageData view:(TextInputView *)view
{
    [SVProgressHUD show];
    FileUpLoadAPI *api = [FileUpLoadAPI new];
    
    typeof(self) self_ = self;
    [api upLoadFileWithURL:FILEUPLOAD_VIDEO_BASE_URL fileData:imageData smallWidth:nil smallHeigth:nil fileType:@"image/jpeg" fileName:@"xxx.jpeg" result:^(BOOL success, NSString *path, NSString *msg) {
        if (success) {
            [self_ sendData:path type:LeaveWordsTypeOfImage];
        }else{
            [SVProgressHUD dismiss];
        }
    }];
    
    
}

-(void)voiceSendedWithVoiceData:(NSData *)voiceData view:(TextInputView *)view
{
    
    [SVProgressHUD show];
    FileUpLoadAPI *api = [FileUpLoadAPI new];
    
    typeof(self) self_ = self;
    [api upLoadFileWithURL:FILEUPLOAD_VIDEO_BASE_URL fileData:voiceData smallWidth:nil smallHeigth:nil fileType:@"video/wav" fileName:@"xxx.wav" result:^(BOOL success, NSString *path, NSString *msg) {
        if (success) {
            [self_ sendData:path type:LeaveWordsTypeOfVoice];
        }else{
            [SVProgressHUD dismiss];
        }
    }];
}


-(void)sendData:(NSString *)data type:(LeaveWordsType)wordstype
{
    NSString *text = nil;
    NSString *img = nil;
    NSString *sou = nil;
    
    switch (wordstype) {
        case LeaveWordsTypeOfText:
            text = data;
            break;
        case LeaveWordsTypeOfImage:
            img = data;
            break;
        case LeaveWordsTypeOfVoice:
            sou = data;
            break;
            
        default:
            break;
    }
    
    int type = -1;
    switch (_part) {
        case InterlocutionPartOfCompere:
        {
            type = CommentTypeForCompereLeave;
        }
            break;
        case InterlocutionPartOfSpectator:
        {
            type = CommentTypeForLiveLeave;
        }
            break;
        case InterlocutionPartOfMyself:
        {
            type = CommentTypeForFeedback;
        }
            break;
        
        default:
            break;
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setLocale:[NSLocale currentLocale]];
    
    LeaveWordItem *item = [LeaveWordItem new];
    item.leaveWordType = 3;
    item.cmtUserName = [UserModel sharedModel].userInfo.nickName;
    item.cmtDt = [formatter stringFromDate:[NSDate date]];
    item.cmtContent = text;
    item.picUrl = img;
    item.soundUrl = sou;
    
    [_listArr addObject:item];
    [_tableView beginUpdates];
    [_tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[_listArr count]-1 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
    [_tableView endUpdates];
    
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_listArr count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
    
    [[CompereModel sharedModel]manageLeaveWordsWithOper:OperTypeAdd cmtType:type cmtId:nil cmtContent:text soundUrl:sou picUrl:img cmtTarget:_cmtTarget replyCmtId:nil result:^(BOOL success, NSString *msg) {
        NSLog(@"%@",msg);
        
        [SVProgressHUD dismiss];
    }];

}

-(void)playTrafficRadio:(LeaveWordItem *)item
{
    if (_voicingIndexPath && _videoPlayer.isPlaying) {
        [_videoPlayer stopPlaying];
        _voicingIndexPath = nil;
    }else{
        
        typeof(self) self_ = self;
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        
        NSURL *URL = [NSURL URLWithString:item.soundUrl];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL*(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) firstObject]];
            NSArray *items = [item.soundUrl componentsSeparatedByString:@"/"];
            
            return [documentsDirectoryPath URLByAppendingPathComponent:[items lastObject]];
        } completionHandler:^(NSURLResponse *response, NSURL*filePath, NSError *error) {
            NSLog(@"File downloaded to: %@", filePath);
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSData *fileData = [fileManager contentsAtPath:filePath.path];
            
            [self_.videoPlayer playAudioWithSpeexData:fileData];
            LeaveWordsTableViewCell *cell = self_.voicingIndexPath ? (LeaveWordsTableViewCell *)[self_.tableView cellForRowAtIndexPath:self_.voicingIndexPath] : nil;
            [cell startVoice];
        }];
        [downloadTask resume];
        
    }
    
}

-(void)playingCompleteOrUserStopWithFile:(NSString *)filePath
{
    if (_voicingIndexPath) {
        LeaveWordsTableViewCell *cell = _voicingIndexPath ? (LeaveWordsTableViewCell *)[_tableView cellForRowAtIndexPath:_voicingIndexPath] : nil;
        
        if (cell) {
            [cell stopVoice];
        }
        
        _voicingIndexPath = nil;
    }
}


-(void)dealloc
{
    [self.view removeKeyboardControl];
}
@end
